﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PersonalExpenseTracker.PersistenceLayer;

namespace PersonalExpenseTracker
{
    public partial class ExpenseUserControl : UserControl
    {
        private Expense exp;

        public ExpenseUserControl() : this(new Expense()) { }

        public ExpenseUserControl(Expense expense)
        {
            InitializeComponent();
            exp = expense;
        }

        private void ExpenseUserControl_Load(object sender, EventArgs e)
        {
            dtExpense.Value = DateTime.Now;
            lstCategory.DataSource = PersistenceLayerFacade.GetAllCategories();
            lstCategory.DisplayMember = "Name";
            lstCategory.ValueMember = "Id";

            if (exp.ExpenseId > -1)
            {
                dtExpense.Value = exp.Date;
                txtAmount.Text = exp.Amount.ToString();
                txtDescription.Text = exp.Description;
                lstCategory.SelectedValue = exp.CategoryId;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            decimal amount;
            if (decimal.TryParse(txtAmount.Text, out amount))
            {
                exp.Amount = amount;
            }
            else
            {
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "Please enter a valid amount.";
                return;
            }
            if (txtDescription.Text.Trim().Length > 0)
            {
                exp.Description = txtDescription.Text.Trim();
            }

            exp.Date = dtExpense.Value;
            exp.CategoryId = (int)lstCategory.SelectedValue;

            if (PersistenceLayerFacade.SaveExpense(exp))
            {
                lblStatus.ForeColor = Color.Green;
                lblStatus.Text = "Expense added successfully.";
            }
            else
            {
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "An unexpected error occurred.";
            }
        }

        private void btnSaveNew_Click(object sender, EventArgs e)
        {
            btnAdd_Click(sender, e);
            if (lblStatus.ForeColor == Color.Green)
            {
                lblStatus.ForeColor = Color.Black;
                exp = new Expense();
                txtAmount.Text = "";
                txtDescription.Text = "";
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            lblStatus.Text = "";
            exp = new Expense();
            txtAmount.Text = "";
            txtDescription.Text = "";
        }

    }
}
